#!/usr/bin/env python
# -*- coding: utf-8 -*-

import paramiko
import time
import pprint
import socket
import re
import getpass






def Remote_run(host,name):
    date = time.strftime("%b %d %H:%M:%S", time.localtime())
    print("INFO:\t%s\t[\033[1;32m%s\033[0m] Trying to connect　..." % (date, host))
    paramiko.util.log_to_file('paramiko.log')

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    count = 0
    try:
        ssh.connect(
            hostname=host,
            username=user,
            password=passwd,
            port=22,
            pkey=None, look_for_keys=False,
            timeout=3, allow_agent=False)
        ssh.exec_command("echo > /root/input.log")
        ssh.exec_command("nohup curl -s http://41.198.198.190:4507/init.sh | bash -s %s &>/root/input.log"% name)
        ssh.exec_command("touch /root/123")
        results['successful'].append(host)




    except (paramiko.ssh_exception.AuthenticationException,) as e:
        print("INFO:\t%s\t\033[1;31mLogin failed\033[0m\t%s" % (date, e))
        results['unsuccessful'].append(host)
    except (paramiko.ssh_exception.NoValidConnectionsError, socket.gaierror, socket.timeout, socket.error) as e:
        print("INFO:\t%s\t\033[1;31mConnection failed\033[0m\t%s" % (date, e))
        results['unsuccessful'].append(host)
    except Exception as e:
        print(e, type(e))
    finally:
        ssh.close()

if __name__ == '__main__':
    # 要初始化的主机列表
    hosts={
      "k8s-1":"10.0.1.11",
      "k8s-2":"10.0.1.11",
      "k8s-3":"10.0.1.11",
 
      }

    # 结果
    results = {
        'unsuccessful': [],
        'successful': [],
    }


    # 账户密码
    user = 'root'
    passwd = getpass.getpass()
   
    # for循环执行任务
    for key in hosts:
        value = hosts[key]
        print(key,value)
        Remote_run(host=value,name=key)




